package com.imufe.chemicalenterprisedangerwarning.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imufe.chemicalenterprisedangerwarning.entity.po.UserPO;
import com.imufe.chemicalenterprisedangerwarning.mapper.UserMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author BaiBan
 * @since 2022/10/13
 */
@Log4j2
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info(username);

        // 根据用户名查询用户信息
        LambdaQueryWrapper<UserPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPO::getUsername, username);
        UserPO user = mapper.selectOne(wrapper);

        // 如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user))
            throw new UsernameNotFoundException(username);

        // 如果存在，查询该用户所具有的权限:RBAC
        List<String> authorities = new LinkedList<>();
//        = mapper.getUserAuthorities(user.getId());

        // 最终封装成UserDetails实现类中返回
        return new UserDetail(user, authorities);
    }
}

